﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using AcctrueWMS.Foundation.Data;
using AcctrueWMS.Foundation.Web;
using System.Text.RegularExpressions;
using System.Collections;
using Newtonsoft.Json.Linq;
using AcctrueWMS.Foundation.DAL;

namespace AcctruePMS.Bll.Manager
{
    public class RoleManager
    {
        #region 角色 功能 节点 授权
        /// <summary>
        /// 获取功能授权tree的数据
        /// </summary>
        /// <returns>查询结果</returns>
        public DataTable GetFunModuleTree()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("key");
            dt.Columns.Add("name");
            dt.Columns.Add("value");
            dt.Columns.Add("text");
            dt.Columns.Add("wbsCode");
            XmlDocument docTree = new XmlDocument();
            string filePath = Runtime.SysFilePath + "\\Startup\\Modules.xml";
            docTree.Load(filePath);
            GetFirstModelTier(docTree, dt);
            GetSecondModelTier(docTree, dt);
            GetModelsActions(docTree, dt);
            return dt;
        }

        /// <summary>
        /// 遍历module.xml 第一层节点
        /// </summary>
        /// <param name="moduleTree">功能节点Tree</param>
        /// <param name="dt">tree表结构</param>
        public void GetFirstModelTier(XmlDocument moduleTree, DataTable dt)
        {
            XmlNodeList firstTierModule = moduleTree.SelectNodes("modules/child/module");
            foreach (XmlNode node in firstTierModule)
            {


                if (Convert.ToBoolean(node.Attributes["showInMenu"].Value))
                {
                    DataRow newRow = dt.NewRow();
                    newRow["key"] = node.Attributes["name"].Value;
                    newRow["name"] = node.Attributes["text"].Value;
                    newRow["value"] = node.Attributes["parent"].Value;
                    newRow["text"] = node.Attributes["showInMenu"].Value;
                    newRow["wbsCode"] = node.Attributes["name"].Value;
                    dt.Rows.Add(newRow);
                }
            }
        }

        /// <summary>
        /// 遍历module.xml 第二层节点
        /// </summary>
        /// <param name="moduleTree">功能节点Tree</param>
        /// <param name="dt">tree表结构</param>
        public void GetSecondModelTier(XmlDocument moduleTree, DataTable dt)
        {
            XmlNodeList secondTierModule = moduleTree.SelectNodes("modules/child/module/child/module");
            foreach (XmlNode node in secondTierModule)
            {
                if (Convert.ToBoolean(node.Attributes["showInMenu"].Value))
                {
                    DataRow newRow = dt.NewRow();
                    newRow["key"] = node.Attributes["name"].Value;
                    newRow["name"] = node.Attributes["text"].Value;
                    newRow["value"] = node.Attributes["parent"].Value;
                    newRow["text"] = node.Attributes["showInMenu"].Value;
                    newRow["wbsCode"] = node.Attributes["name"].Value;
                    dt.Rows.Add(newRow);
                }
            }
        }

        /// <summary>
        /// 遍历module.xml 第三层节点
        /// </summary>
        /// <param name="moduleTree">功能节点Tree</param>
        /// <param name="dt">tree表结构</param>
        public void GetModelsActions(XmlDocument moduleTree, DataTable dt)
        {
            XmlNodeList ModuleAction = moduleTree.SelectNodes("modules/child/module/child/module/actions/action");
            foreach (XmlNode action in ModuleAction)
            {
                DataRow actinRow = dt.NewRow();
                actinRow["wbsCode"] = action.ParentNode.ParentNode.Attributes["name"].Value + "." + action.Attributes["maskNo"].Value;
                actinRow["key"] = action.ParentNode.ParentNode.Attributes["name"].Value + "." + action.Attributes["maskNo"].Value;
                actinRow["name"] = action.Attributes["displayName"].Value;
                actinRow["text"] = action.Attributes["name"].Value;
                actinRow["value"] = action.Attributes["maskNo"].Value;
                dt.Rows.Add(actinRow);
            }

        }
        private IDataModelContext context = Runtime.Context;

        /// <summary>
        /// 查询岗位授权信息
        /// </summary>
        /// <param name="roleCode">岗位编码</param>
        /// <param name="modelName">岗位授权信息表名</param>
        /// <returns>返回json串</returns>
        public string GetRoleCheckTree(string roleCode, string modelName)
        {
            DataTable roles = WMSqlExcuter.ExecuteDataTable(string.Format("select * from {0}  where roleCode='{1}'", modelName, roleCode));
            DataTable MaskRoleArr = WMSqlExcuter.ExecuteDataTable(string.Format("select * from {0}  where roleCode='{1}' and privilegemask<>0", modelName, roleCode));
            foreach (DataRow item in roles.Select("privilegemask<>0"))
            {
                roles.Rows.Remove(item);
            }
            for (int i = 0; i < MaskRoleArr.Rows.Count; i++)
            {
                int intRole = int.Parse(MaskRoleArr.Rows[i]["privilegemask"].ToString());
                string roleBinary = Convert.ToString(intRole, 2);
                char[] charRoleArr = roleBinary.ToCharArray().Reverse().ToArray();

                for (int j = 0; j < charRoleArr.Length; j++)
                {
                    if (charRoleArr[j].ToString() == "1")
                    {
                        DataRow newDtRow = roles.NewRow();
                        newDtRow["rolecode"] = roleCode;
                        newDtRow["privilegemask"] = j + 1;
                        newDtRow["modulewbs"] = MaskRoleArr.Rows[i]["modulewbs"].ToString() + "." + newDtRow["privilegemask"].ToString();
                        roles.Rows.Add(newDtRow);
                    }
                }
                DataRow newNodeDtRow = roles.NewRow();
                newNodeDtRow["rolecode"] = roleCode;
                newNodeDtRow["privilegemask"] = 0;
                newNodeDtRow["modulewbs"] = MaskRoleArr.Rows[i]["modulewbs"].ToString();
                roles.Rows.Add(newNodeDtRow);
            }

            return JsonTableConverter.SerializeObject(roles);
        }

        /// <summary>
        /// 保存角色授权树
        /// </summary>
        /// <param name="rolecode">岗位编码</param>
        /// <param name="treeNodes">选中节点表达式</param>
        /// <param name="modelName">dataModel</param>
        /// <returns>执行结果</returns>
        public string SaveTreeNodes(string rolecode, string treeNodes, string modelName)
        {
            Dictionary<string, RoleTemp> roleList = new Dictionary<string, RoleTemp>();
            JArray ja = JArray.Parse(treeNodes);
            DataModel changeModel = new DataModel(context, modelName);
            changeModel.Delete(" where roleCode='" + rolecode + "'");//删除相应角色的所有授权节点
            for (int i = 0; i < ja.Count; i++)
            {
                bool check = Convert.ToBoolean(ja[i]["Check"].ToString());
                if (check == true)
                {
                    int InfoMask = 1;
                    string wbs = ja[i]["Wbs"].ToString();
                    string Mask = ja[i]["Mask"].ToString();
                    //DataModel newRow = changeModel.NewRow();
                    RoleTemp node = new RoleTemp();
                    //将树节点数据实例化为RoleTemp类
                    foreach (DataModelColumn column in changeModel.Columns)
                    {
                        switch (column.Name)
                        {
                            case "roleCode": node.RoleCode = rolecode; break;
                            case "moduleWBS": node.wbs = wbs; break;
                            case "privilegeMask": node.Mask = int.Parse(Mask) > 0 ? (InfoMask << int.Parse(Mask) - 1) : 0; break;// InfoMask << ((int.Parse(Mask)-1) > 0 ? (int.Parse(Mask)-1) : 0); break;
                        }
                    }
                    int dotLen;//存储wbscode 的中的点节点长度信息
                    dotLen = wbs.LastIndexOf('.') == -1 ? wbs.Length : (wbs.Split('.').Length > 2) ? wbs.LastIndexOf(".") : wbs.Length;
                    string pwbs = node.wbs.Substring(0, dotLen);
                    if (roleList.ContainsKey(pwbs))
                    {
                        roleList[pwbs].Mask = roleList[pwbs].Mask | node.Mask;
                    }
                    else
                    {
                        roleList.Add(node.wbs, node);
                    }
                }
            }
            foreach (KeyValuePair<string, RoleTemp> item in roleList)
            {
                DataModel newRow = changeModel.NewRow();
                newRow["roleCode"].Value = item.Value.RoleCode;
                newRow["moduleWBS"].Value = item.Value.wbs;
                newRow["privilegeMask"].Value = item.Value.Mask;
                changeModel.Rows.Add(newRow);
            }
            if (changeModel.Rows.Count > 0)
            {
                changeModel.Save("1");
            }

            return "tree save success";
        }
        #endregion

        #region 角色 货位授权
        /// <summary>
        /// 获取以授权的货位树
        /// </summary>
        /// <returns></returns>
        public string GetSysWarehouseDepotsTree(string roleCode, string modelName)
        {
            DataModel ModelTree = new DataModel(context, modelName);
            string QueryStr = " roleCode='" + roleCode + "'";
            ModelTree.Select(QueryStr);
            DataTable dt = ModelTree.ToDataTable();
            return JsonTableConverter.SerializeObject(dt);
        }
        //
        /// <summary>
        /// 保存角色岗位授权树
        /// </summary>
        /// <param name="rolecode">岗位编码</param>
        /// <param name="treeNodes">选择中节点表达式</param>
        /// <param name="modelName">dataModel</param>
        /// <returns>执行结果</returns>
        public string SaveRoleDepotPermission(string rolecode, string treeNodes, string modelName)
        {
            JArray ja = JArray.Parse(treeNodes);
            DataModel changeModel = new DataModel(context, modelName);
            changeModel.Delete(string.Format(" where roleCode='{0}'", rolecode));//删除所有节点
            for (int i = 0; i < ja.Count; i++)
            {
                bool check = Convert.ToBoolean(ja[i]["Check"].ToString());
                if (check == true)
                {
                    //string wbs = ja[i]["Wbs"].ToString(); //wbs
                    string Mask = ja[i]["privilegeMask"].ToString(); //权限掩码//是页面生成节点的顺序；
                    string Ware = ja[i]["depotWBS"].ToString();  // 仓库编码

                    DataModel newRow = changeModel.NewRow();
                    foreach (DataModelColumn column in newRow.Columns)
                    {
                        switch (column.Name)
                        {
                            case "roleCode": newRow[column.Name].Value = rolecode; break;//
                            case "depotWBS": newRow[column.Name].Value = Ware; break;//wbs
                            case "privilegeMask": newRow[column.Name].Value = Convert.ToInt32(Mask); break;
                        }
                    }
                    changeModel.Rows.Add(newRow);
                }
            }
            if (changeModel.Rows.Count > 0)
            {
                changeModel.Save("1");//保存
            }

            return "tree save success";
        }
        #endregion

        #region  用户  角色 授权 相关方法;

        /// <summary>
        /// 保存岗位授权
        /// </summary>
        /// <param name="userNo">用户编码</param>
        /// <param name="roles">对应的岗位</param>
        /// <param name="modelName">dataModel</param>
        /// <returns>执行结果</returns>
        public string SaveUserRolePermission(string userNo, string roles, string modelName)
        {
            JArray Jarr = JArray.Parse(roles);
            DataModel model = new DataModel(context, modelName);
            for (int i = 0; i < Jarr.Count; i++)
            {
                string role = Jarr[i]["value"].ToString();
                bool chk = Convert.ToBoolean(Jarr[i]["check"].ToString());
                if (chk)
                {
                    DataModel querydata = new DataModel(context, modelName);
                    querydata.Select(string.Format(" userNo='{0}' and roleCode='{1}' ", userNo, role));
                    if (querydata.Rows.Count == 0)
                    {
                        DataModel newRow = model.NewRow();
                        foreach (DataModelColumn column in newRow.Columns)
                        {
                            switch (column.Name)
                            {
                                case "userNo": newRow[column.Name].Value = userNo; break;
                                case "roleCode": newRow[column.Name].Value = role; break;
                            }
                        }
                        model.Rows.Add(newRow);
                    }
                }
                else//保存取消权限
                {
                    DataModel delmodel = new DataModel(context, modelName);
                    string delstr = " where userNo='" + userNo + "' and roleCode='" + role + "'";
                    delmodel.Delete(delstr);
                }
            }
            if (model.Rows.Count > 0)//保存用户 角色权限
            {
                model.Save("1");
            }
            return "save success";
        }

        /// <summary>
        /// 初始化用户权限
        /// </summary>
        /// <param name="userNo">用户编码</param>
        public string InitUserRole(string userNo, string modelName)
        {
            DataModel userRole = new DataModel(context, modelName);
            userRole.Select(string.Format(" userNo='{0}' ", userNo));
            DataTable dt = userRole.ToDataTable();
            if (dt.Rows.Count > 0)
            {
                return JsonTableConverter.SerializeObject(dt);
            }
            else
            {
                return "";
            }
        }
        #endregion

    }
    public class RoleTemp
    {
        public string wbs
        {
            get;
            set;
        }
        public bool Check
        {
            get;
            set;
        }
        public int Mask
        {
            get;
            set;
        }
        public string RoleCode
        {
            get;
            set;
        }
    }
}
